package com.syc.solr_demo;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 索引
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class solrTest01 {
    @Autowired
    private SolrClient solrClient;

    /**
     * 测试添加
     */
    @Test
    public void test01() throws IOException, SolrServerException {
        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id", "889900");
        doc.setField("name", "测试商品");

        UpdateResponse add = solrClient.add(doc);
        System.out.println(add.getStatus());//0成功
        //提交事务
        solrClient.commit();
    }

    /**
     * 批量添加
     */
    @Test
    public void test011() throws IOException, SolrServerException {
        List<SolrInputDocument> list = new ArrayList<>();
        SolrInputDocument doc1 = new SolrInputDocument();
        doc1.setField("id", "2");
        doc1.setField("name", "小米手机");
        SolrInputDocument doc2 = new SolrInputDocument();
        doc2.setField("id", "3");
        doc2.setField("name", "每个人都一有双手");
        SolrInputDocument doc3 = new SolrInputDocument();
        doc3.setField("id", "4");
        doc3.setField("name", "华为智慧屏");
        SolrInputDocument doc4 = new SolrInputDocument();
        doc4.setField("id", "5");
        doc4.setField("name", "华为是5g领先者");

        list.add(doc1);
        list.add(doc2);
        list.add(doc3);
        list.add(doc4);
        UpdateResponse add = solrClient.add(list);

        System.out.println(add.getStatus());//0成功
        //提交事务
        solrClient.commit();
    }


    /**
     * 测试修改
     */
    @Test
    public void test02() throws IOException, SolrServerException {
        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id", "889900");
        doc.setField("name", "测试商品（测试修改）");

        UpdateResponse add = solrClient.add(doc);
        System.out.println(add.getStatus());//0成功
        //提交事务
        solrClient.commit();
    }

    /**
     * 测试删除(根据id)
     */
    @Test
    public void test03() throws IOException, SolrServerException {
        UpdateResponse updateRes = solrClient.deleteById("889900");
        System.out.println(updateRes.getStatus());//0成功
        //提交事务
        solrClient.commit();
    }

}
